If it is still under warranty book into an apple store and get them to do a battery diagnostic. They may even replace it if it is faulty. If it is not under warranty you could try a re-calibration before replacing the battery. Sometimes the sensor that tracks the current going in and out of the battery loses track and needs to be reset.
If you want to try and re-calibrate a battery that is shutting off early do the following (will take a bit of time and patience).
1. When iPhone switches off (30-40%), plug it back in until it switches on (do not let it charge up) then immediately unplug it and keep using it.
2. You should find it will run down further this time before switching off. Repeat this first step over and over until you get down to 1% and it switches off. I have done this on a 4S and 5 and took 3-4 goes.
3. Once it has gotten to 0% and is off, plug it in and leave it charging to 100%, leave it plugged in for an extra hour or two.
4. When it is at 100% hold down the on/off and home button together until the screen goes black and an apple logo appears (soft reset), you will not lose anything and the phone will reboot. Use phone as normal.
5. Use your phone until it fully drains again and do not top up charge until it gets to zero. Plug it back in and charge to 100% then do the soft reset. Hopefully it works as normal after this.
6. If it shuts down early again after the first run through this process but is getting better, then go through the process again. If you find no change after 2-3 goes then it is probably time for a new battery.
I hope this helps.